<!-- 公寓楼 -->
<template>
  <div class="app-container">
    <!-- 搜索 -->
    <template v-if="showType == 0">
      <searchForm :formOptions="formOptions" @onSearch="onSearch" :formLabelWidth="formLabelWidth" @onReset="onReset"
        v-show="showSearch" />
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['dorm:house:add']">新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="oneAdd = true">一键新增</el-button>
      </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table @cell-dblclick="tableClick" :data="tablelist" v-loading="loading">
        <el-table-column label="名称" prop="houseName" :show-overflow-tooltip="true" align="center" />
        <el-table-column label="编号" prop="houseNo" align="center" />
        <el-table-column label="负责人" prop="personName" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="showPersonName(scope.row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="260">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
              v-hasPermi="['dorm:house:edit']">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['dorm:house:remove']">删除</el-button>
            <!-- <el-button size="mini" type="text" @click="handleDelete(scope.row)">清空人员</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">设置角色</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
      <!-- 添加或修改公寓楼对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="houseName">
                <el-input v-model="form.houseName" placeholder="请输入名称" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号" prop="houseNo">
                <el-input v-model="form.houseNo" placeholder="请输入编号" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="userHouseListId">
                <el-select filterable remote v-model="form.userHouseListId" multiple placeholder="请选择负责人"
                  :remote-method="remoteMethod" style="width: 100%">
                  <el-option v-for="dict in alluserList" :key="dict.userId" :label="dict.nickName" :value="dict.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 一键添加 -->
      <el-dialog :title="title" :visible.sync="oneAdd" width="60%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="houseName">
                <el-input v-model="form.houseName" placeholder="请输入名称" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号" prop="houseNo">
                <el-input v-model="form.houseNo" placeholder="请输入编号" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收费标准" prop="chargeStandard">
                <el-select v-model="form.chargeStandard" placeholder="请选择收费标准" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_charging_standards" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类型" prop="roomType">
                <el-select v-model="form.roomType" placeholder="请选择房间类型" style="width: 100%">
                  <el-option v-for="dict in dict.type.sys_room_type" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属角色" prop="belongRoleId">
                <el-select v-model="form.belongRoleId" placeholder="请选择所属角色" style="width: 100%">
                  <el-option v-for="dict in alluserList" :key="dict.userId" :label="dict.nickName" :value="dict.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总层数" prop="totalFloor">
                <el-input v-model="form.totalFloor" placeholder="请输入总层数" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间/层" prop="totalRoom">
                <el-input v-model="form.totalRoom" placeholder="请输入房间/层" maxlength="30" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="oneAdd = false">取 消</el-button>
        </div>
      </el-dialog>
    </template>

    <template v-else>
      <el-row :gutter="20">
        <el-col :span="4">
          <leftHouseTree noRoom @treeDbClick="treeDbClick"></leftHouseTree>
        </el-col>
        <el-col :span="20">
          <el-page-header v-if="showType != 0" @back="goback" content="返回楼栋列表"></el-page-header>
          <apartmentFloor :houseId="houseId" v-if="showType == 1"></apartmentFloor>
          <apartmentRoom :floorId="floorId" v-else-if="showType == 2"></apartmentRoom>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script>
import searchForm from "@/components/Search/searchForm.vue";
import { mapState, mapActions } from 'vuex'
import apartmentFloor from "./apartmentFloor.vue";
import apartmentRoom from "./apartmentRoom.vue";
import leftHouseTree from "./leftHouseTree.vue"
export default {
  name: "Role",
  dicts: ["sys_charging_standards", "sys_room_type", "sys_user_sex"],
  components: {
    searchForm, apartmentFloor,
    apartmentRoom,
    leftHouseTree
  },
  data() {
    return {
      formLabelWidth: "50px",
      formOptions: [
        {
          label: "名称",
          prop: "houseName",
          element: "el-input",
          placeholder: "请输入名称",
        },
        {
          label: "编号",
          prop: "houseNo",
          element: "el-input",
          placeholder: "请输入编号",
        },
      ],
      showType: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      oneAdd: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseName: undefined,
        houseNo: undefined,
      },
      // 表单参数
      form: {
        houseName: "",
        houseNo: "",
        chargeStandard: "",
        roomType: "",
        userHouseListId: "",
        totalFloor: '',
        totalRoom: '',
        sex: ''
      },
      // 表单校验
      rules: {
        houseName: [
          { required: true, message: "公寓楼名称不能为空", trigger: "blur" },
        ],
        houseNo: [
          { required: true, message: "公寓楼编号不能为空", trigger: "blur" },
        ],
        // roomType: [
        //   { required: true, message: "房间类型不能为空", trigger: "blur" },
        // ],
        userHouseListId: [
          { required: false, message: "所属用户不能为空", trigger: "blur" },
        ],
        totalFloor: [
          { required: true, message: "总楼层数不能为空", trigger: "blur" },
        ],
        totalRoom: [
          { required: true, message: "房间/层不能为空", trigger: "blur" },
        ],
      },
      floorId: null,
      houseId: null
    };
  },
  computed: {
    ...mapState({
      tablelist: state => state.apartmentBuilding.list,
      alluserList: state => state.apartmentBuilding.sysUserList,
    })
  },

  props: {
    noClick: Boolean
  },

  async created() {
    this.checkType()
    await this.getAllUser({
      roleKeyList: ['dorm', 'dormHouse'],
      userType: '01'
    })
    this.getList();
    console.log(this.$route)

  },
  methods: {
    ...mapActions({
      getTableList: 'apartmentBuilding/getTable',
      getAllUser: 'apartmentBuilding/getSystemUser',
      addHouse: 'apartmentBuilding/addHouse',
      putHouseInfoById: 'apartmentBuilding/putHouseInfoById',
      delHouseInfoById: 'apartmentBuilding/delHouseInfoById',
      getAllRoom: 'apartmentBuilding/allInfolist',
    }),

    // 判断是进入哪个类型
    checkType() {
      if (this.$route.query.floorId && this.$route.query.floorId) {
        this.showType = 2
      } else if (this.$route.query.houseId) {
        this.showType = 1
      } else {
        this.showType = 0
      }
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      this.getTableList(this.queryParams).then(res => {
        this.total = res.total
        this.loading = false
      })
    },
    // 获取搜索表单提交的数据
    onSearch(val) {
      // 查询条件和分页数据合并
      const arr = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
      this.$emit("searchHouse", val)
    },
    // 重置
    onReset(data) {
      this.queryParams.pageNum = 1;
      const arr = Object.assign(this.queryParams, data);
      this.getList();
      this.$emit("searchHouse", data)
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true;
      this.title = "添加公寓楼";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 回显 管理人员 改造数据
      let arr = []
      row.userHouseList.map(es => {
        arr.push(es.userId)
      })

      row.userHouseListId = arr
      this.form = { ...row }

      this.form.roomType = row.roomType + ''
      this.form.chargeStandard = row.chargeStandard + ''
      this.form.sex = row.sex + ''
      this.open = true;
      this.title = "修改信息";
    },

    /** 提交按钮 */
    submitForm: function async() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (!this.form.houseId) {
            const { data, code } = await this.addHouse(this.form)
            if (code == 200) {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
              this.getAllRoom();
            }
          } else {
            const { data, code } = await this.putHouseInfoById(this.form)
            if (code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getAllRoom();
            }
          }

          this.reset()
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const houseIds = row.houseId || this.ids;
      this.$modal
        .confirm('是否确认删除名称为"' + row.houseName + '"的数据项？')
        .then(async () => {
          const { data, code } = await this.delHouseInfoById({ houseIds })
          this.getList();
          this.getAllRoom();
          this.$modal.msgSuccess("删除成功");
        })

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/role/export",
        {
          ...this.queryParams,
        },
        `role_${new Date().getTime()}.xlsx`
      );
    },


    // 楼栋被双击后 进入楼层表格

    tableClick(row) {
      if (this.noClick) {
        return
      }
      this.$router.push({
        path: '/apartment/apartment/apartmentBuilding',
        query: {
          houseId: row.houseId
        }
      })

      this.showType = 1
    },


    // 返回楼栋列表
    goback() {
      this.$router.push({
        path: '/apartment/apartment/apartmentBuilding',
        query: null
      })
      this.showType = 0

    },

    // 回显负责人名称
    showPersonName(row) {
      let userHouseList = row.userHouseList

      if(userHouseList.length<1){
        this.$message.error("当前楼栋暂未设置负责人,请先设置负责人")
        setTimeout(()=>{
          this.handleUpdate(row)
        },1000)
        return
      }
      const h = this.$createElement;
      let htmlArr = [];
      userHouseList.map(res => {
        htmlArr.push(h('span', { style: 'margin-right:10px' }, '姓名：' + res.nickName))
        htmlArr.push(h('span', { style: 'color: teal' }, '手机号: ' + (res.phonenumber || "")))
        htmlArr.push(h('br'))
      })
      this.$msgbox({
        title: `${row.houseName}的负责人`,
        message: h('p', null, htmlArr),
        showConfirmButton: false,
        showCancelButton: false,
      })
    },

    treeDbClick(row) {

      this.$router.push({
        path: '/apartment/apartment/apartmentBuilding',
        query: {
          houseId: row.houseId,
          floorId: row.floorId
        }
      })
      // 左侧 tree 点击后 改变选中的floorid 和 houseid
      this.floorId = row.floorId
      this.houseId = row.houseId
      if (row.houseId && row.floorId) {
        this.showType = 2
      } else {
        this.showType = 1
      }
    },

    // 宿舍管理员远程搜索
    async remoteMethod(query) {
      await this.getAllUser({
        roleKeyList: ['dorm', 'dormHouse'],
        userType: '01',
        keywords: query
      })
    }
  },
  watch: {
    $route: {
      handler: function (val, oldVal) {
        this.checkType()
      },
      // 深度观察监听
      deep: true
    }
  },
};
</script>
